package com.gyy.flutter.plugin.flutter_plugin_print_a300

import androidx.annotation.NonNull
import com.gyy.flutter.plugin.flutter_plugin_print_a300.app.YmApp
import com.gyy.flutter.plugin.flutter_plugin_print_a300.common.BluetoothUtil
import com.gyy.flutter.plugin.flutter_plugin_print_a300.common.StringUtil
import com.gyy.flutter.plugin.flutter_plugin_print_a300.newprint.HMA300PrintLogic
import com.gyy.flutter.plugin.flutter_plugin_print_a300.newprint.base.PrintKey

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FlutterPluginPrintA300Plugin */
class FlutterPluginPrintA300Plugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    YmApp.context = flutterPluginBinding.applicationContext
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_plugin_print_a300")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else if (call.method == "nativePrint") { //打印
      nativePrint(call);
      result.success("nativePrint000")
    } else if (call.method == "addressList") { //获取连接的设备
      var addressList = addressList(call)
      result.success(addressList)
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  //获取蓝牙列表
  fun addressList(@NonNull call: MethodCall): ArrayList<Map<String, String>> {
    var addressList = ArrayList<Map<String, String>>()
    val bluetoothAble = BluetoothUtil.getBluetoothAble()
    if (!StringUtil.isEmpty(bluetoothAble)) {
      return addressList
    }
    addressList = BluetoothUtil.addressList
    return addressList;
  }

  fun nativePrint(@NonNull call: MethodCall) {
    //解析参数
    val dataMap: HashMap<String, String>? = call.argument(PrintKey.DATA_JSON)
    val blueAddress: String? = call.argument(PrintKey.BLUE_ADDRESS)

     HMA300PrintLogic().printLayout(dataMap, blueAddress)
  }

}
